<script setup>
import { ref, reactive, onMounted, watch, inject } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { globalStore } from '@/stores/global.js'

import {
  UploadFilled,
  Search,
  WarningFilled,
  ArrowUpBold,
  ArrowDownBold,
  Back,
  Right,
  CircleCheckFilled,
  Tools,
  Loading,
  Download,
  QuestionFilled,
  Plus,
  Minus,
  Refresh,
  EditPen,
  DeleteFilled,
} from '@element-plus/icons-vue'

import NetworkIcon from '@/components/icons/NetworkIcon.vue'
import AddModuleIcon from '@/components/icons/AddModuleIcon.vue'
import ModuleIcon from '@/components/icons/ModuleIcon.vue'
import AddNetElemenetIcon from '@/components/icons/AddNetElemenetIcon.vue'

const storeGlobal = globalStore()
const $http = inject('$http')

const moduleDialogRef = ref(null)
const netDialogRef = ref(null)
const state = reactive({
  show: false,
  netElement: [],

  netDialogVisible: false,
  netDialogState: 'Add',
  netDialogForm: {},
  netDialogFormRules: {
    netElementId: [{ required: true, message: '请输入网元ID', trigger: 'blur' }],
    topologyName: [{ required: true, message: '请输入网元名称', trigger: 'blur' }],
  },

  moduleDialogVisible: false,
  moduleDialogState: 'Add',
  moduleDialogForm: {},
  moduleDialogFormRules: {
    moduleName: [{ required: true, message: '请输入模块名称', trigger: 'blur' }],
    upgradeOrder: [{ required: true, message: '请输入升级顺序', trigger: 'blur' }],
  },
})

onMounted(() => {
  getTopologyList()
})

async function getTopologyList() {
  let netElementList = []
  let topologyList = await $http('/api/topology/list')
  // for (let i = 0; i < topologyList.length; i++) {
  //   const element = topologyList[i]
  //   let moduleList = await $http('/api/module/list?topologyId=' + element.topologyId)
  //   element.children = moduleList
  //   netElementList.push(element)
  // }
  state.netElement = topologyList
}
function openModuleDialog(type, item) {
  state.moduleDialogVisible = true
  state.moduleDialogState = type
  if (type == 'Add') {
    state.moduleDialogForm.topologyId = item.topologyId
  } else {
    state.moduleDialogForm = item
  }
}
function openNetDialog(type, item) {
  if (type == 'Edit') {
    state.netDialogForm = { ...item, ...state.netDialogForm }
  }
  state.netDialogState = type
  state.netDialogVisible = true
  console.log(state.netDialogForm, '网元修改')
}
function closeDialog(type) {
  if (type == 'net') {
    state.netDialogVisible = false
    state.netDialogForm = {}
  } else {
    state.moduleDialogVisible = false
    state.moduleDialogForm = {}
  }
}
function netSubmit() {
  netDialogRef.value.validate((error) => {
    if (error) {
      if (state.netDialogState == 'Add') {
        $http.post('/api/topology/add', state.netDialogForm).then((res) => {
          ElMessage.success('新增成功')
          state.netDialogVisible = false
          state.netDialogForm = {}
          getTopologyList()
        })
      } else {
        delete state.netDialogForm.createTime
        delete state.netDialogForm.children
        delete state.netDialogForm.modules
        $http.put('/api/topology/edit', state.netDialogForm).then((res) => {
          ElMessage.success('修改成功')
          state.netDialogVisible = false
          state.netDialogForm = {}
          getTopologyList()
        })
      }
    }
  })
}
function moduleSubmit() {
  moduleDialogRef.value.validate((error) => {
    if (error) {
      if (state.moduleDialogState == 'Add') {
        $http.post('/api/module/add', state.moduleDialogForm).then((res) => {
          ElMessage.success('新增成功')
          state.moduleDialogVisible = false
          getTopologyList()
        })
      } else {
        delete state.moduleDialogForm.createTime
        $http.post('/api/module/update', state.moduleDialogForm).then((res) => {
          ElMessage.success('编辑成功')
          state.moduleDialogVisible = false
          getTopologyList()
        })
      }
    }
  })
}
function deleteChange(type, item) {
  let contentTxt =
    type == 'net'
      ? `您确定要删除网元拓扑 [${item.netElementId}] 吗？此操作将删除该网元下的所有模块，且不可撤销。`
      : `您确定要删除模块 [${item.moduleName}]（升级顺序: ${item.upgradeOrder}）吗？此操作不可撤销。`
  ElMessageBox.confirm(contentTxt, '确认删除', {
    confirmButtonText: '确认删除',
    cancelButtonText: '取消',
    type: 'none',
  })
    .then(() => {
      let url =
        type == 'net'
          ? '/api/topology/delete?topologyId=' + item.topologyId
          : '/api/module/delete?moduleId=' + item.moduleId
      $http.delete(url).then((res) => {
        ElMessage.success('删除成功')
        getTopologyList()
      })
    })
}
async function onOperation(type){
  if (type == 'unfold') {
    // if(state.show) return;
    state.show = true;
    // let netElementList = []
    // let topologyList = await $http('/api/topology/list')
    // for (let i = 0; i < topologyList.length; i++) {
    //   const element = topologyList[i]
    //   let moduleList = await $http('/api/module/list?topologyId=' + element.topologyId)
    //   element.children = moduleList
    //   netElementList.push(element)
    // }
    // state.netElement = netElementList
  }else{
    state.show = false;
  }
}
</script>
<template>
  <div class="box-css topology-content">
    <div class="topology-content-title flex-center-between">
      <div>拓扑结构列表</div>
      <div class="topology-content-title-icon-list">
        <el-icon class="cursor-pointer" @click="getTopologyList"><Refresh /></el-icon>
        <AddNetElemenetIcon
          width="16"
          height="16"
          class="cursor-pointer"
          @click="openNetDialog('Add')"
        />
        <el-icon class="cursor-pointer" @click="onOperation('unfold')"><Plus /></el-icon>
        <el-icon class="cursor-pointer" @click="onOperation('contraction')"><Minus /></el-icon>
      </div>
    </div>
    <div class="topology-network-element">
      <div
        class="topology-network-element-item"
        v-for="item in state.netElement"
        :key="item.topologyId"
      >
        <div class="topology-network-element-item-title flex-center-between">
          <div class="topology-network-element-item-title-left flex-center">
            <NetworkIcon width="20" height="20" />
            <span>网元拓扑 [{{ item.netElementId }}]</span>
          </div>
          <div class="topology-network-element-item-title-right">
            <el-icon class="cursor-pointer highlight" @click="openNetDialog('Edit', item)">
              <EditPen/>
            </el-icon>
            <AddModuleIcon
              width="18"
              height="18"
              class="cursor-pointer"
              @click="openModuleDialog('Add', item)"
            />
            <el-icon class="cursor-pointer danger" @click="deleteChange('net', item)"><DeleteFilled /></el-icon>
          </div>
        </div>
        <div class="topology-network-element-item-module-list" v-show="state.show">
          <div
            class="topology-network-element-item-module flex-center-between"
            v-for="moduleItem in item.modules"
            :key="moduleItem.upgradeOrder"
          >
            <div class="topology-network-element-item-module-left">
              <ModuleIcon class="mar-right" width="14" height="14" />
              <span>模块 [{{ moduleItem.moduleName }}] </span>
              <span class="gray text-sm">(升级顺序: {{ moduleItem.upgradeOrder }})</span>
            </div>
            <div class="topology-network-element-item-module-right">
              <el-icon
                class="cursor-pointer highlight"
                @click="openModuleDialog('Edit', moduleItem)"
                ><EditPen
              /></el-icon>
              <el-icon class="cursor-pointer danger"  @click="deleteChange('module', moduleItem)"><DeleteFilled /></el-icon>
            </div>
          </div>
        </div>
      </div>
      <div v-show="state.netElement.length == 0">
        <el-empty description="暂无数据" />
      </div>
    </div>
  </div>
  <el-dialog
    v-model="state.moduleDialogVisible"
    :title="state.moduleDialogState == 'Add' ? '新增模块' : '编辑模块'"
    width="500"
    @close="closeDialog('module')"
    align-center
  >
    <el-form
      :model="state.moduleDialogForm"
      :rules="state.moduleDialogFormRules"
      ref="moduleDialogRef"
      label-width="auto"
    >
      <el-form-item label="模块名称" prop="moduleName">
        <el-input v-model="state.moduleDialogForm.moduleName" placeholder="例如：module-name" />
      </el-form-item>
      <el-form-item label="升级顺序" prop="upgradeOrder">
        <el-input v-model="state.moduleDialogForm.upgradeOrder" placeholder="例如：1" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeDialog('module')">取消</el-button>
        <el-button color="rgba(22, 93, 255, 1)" @click="moduleSubmit">保存</el-button>
      </div>
    </template>
  </el-dialog>
  <el-dialog
    v-model="state.netDialogVisible"
    :title="state.netDialogState == 'Add' ? '新增网元拓扑' : '编辑网元拓扑'"
    @close="closeDialog('net')"
    width="500"
    align-center
  >
    <el-form
      :model="state.netDialogForm"
      :rules="state.netDialogFormRules"
      ref="netDialogRef"
      label-width="auto"
    >
      <el-form-item label="网元ID" prop="netElementId">
        <el-input v-model="state.netDialogForm.netElementId" placeholder="例如：NCP2" />
      </el-form-item>
      <el-form-item label="网元名称" prop="topologyName">
        <el-input v-model="state.netDialogForm.topologyName" placeholder="例如：netrowk-element-2" />
      </el-form-item>
      <el-form-item label="描述">
        <el-input
          type="textarea"
          autosize
          :rows="2"
          v-model="state.netDialogForm.description"
          placeholder="请输入网元描述信息"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeDialog('net')">取消</el-button>
        <el-button color="rgba(22, 93, 255, 1)" @click="netSubmit">保存</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<style scoped lang="less">
.topology-content {
  .topology-network-element {
    padding: 16px;
    .mar-right {
      margin-right: 8px;
    }
    .topology-network-element-item {
      .topology-network-element-item-module:hover {
        background-color: rgba(22, 93, 255, 0.05);
      }
      .topology-network-element-item-module {
        padding: 8px 12px;
        border-radius: 8px;
        margin-bottom: 8px;
        .topology-network-element-item-module-right {
          display: flex;
          gap: 12px;
          font-size: 16px;
        }
      }
      .topology-network-element-item-module-list {
        border-left: 2px solid #c9cdd4;
        margin-left: 12px;
        padding: 0 0 0 16px;
      }
      .topology-network-element-item-title:hover {
        background-color: rgba(22, 93, 255, 0.05);
      }
      .topology-network-element-item-title {
        padding: 8px 12px;
        border-radius: 8px;
        line-height: 36px;
        .topology-network-element-item-title-right {
          display: flex;
          gap: 12px;
        }
        .topology-network-element-item-title-left {
          gap: 8px;
        }
      }
    }
  }
  .topology-content-title {
    padding: 16px;
    background-color: #f9fafb;
    border-bottom: 1px solid #e5e7eb;
    border-radius: 12px 12px 0 0;
    line-height: 36px;
    .topology-content-title-icon-list {
      display: flex;
      gap: 8px;
    }
  }
}
.box-css {
  border: 1px solid #e5e7eb;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
  border-radius: 12px;
  background-color: #ffffff;
}
</style>
